package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Resource
    private SpecParamService specParamService;

    @Override
    public List<SpecGroupDTO> queryGroupsByCategoryId(Long id) {
        List<SpecGroup> specGroupList = this.query().eq("category_id", id).list();
        return SpecGroupDTO.convertEntityList(specGroupList);
    }

    @Override
    public List<SpecGroupDTO> querySpecListByCategoryId(Long id) {

        //获取规格数组
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(this.query().eq("category_id", id).list());
        if (CollectionUtils.isEmpty(specGroupDTOList)){
            throw new LyException(404, "该分类下的规格组不存在！");
        }

        //获取规格参数数组
        List<SpecParamDTO> specParamDTOList = specParamService.querySpecParams(id, null, null);

        //将同一组的规格ID存放
//        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
//            List<SpecParamDTO> paramDTOs = new ArrayList<>();
//            for (SpecParamDTO specParamDTO : specParamDTOList) {
//                if (specGroupDTO.getId() == specParamDTO.getGroupId()){
//                    paramDTOs.add(specParamDTO);
//                    specGroupDTO.setParamDTOs(paramDTOs);
//                }
//            }
//        }
        // TODO   stream方式   //类::实例方法名 获取类里面的一个实例    实例对象->另外一个实例对象 转化为新的
        // 对规格参数分组，groupId一致的在一组
        Map<Long, List<SpecParamDTO>> map = specParamDTOList.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 把参数放入group
//        for (SpecGroupDTO groupDTO : specGroupDTOList) {
//            groupDTO.setParamDTOs(map.get(groupDTO.getId()));
//        }
        specGroupDTOList.stream().forEach(specGroupDTO -> specGroupDTO.setParamDTOs(map.get(specGroupDTO.getId())));
        return specGroupDTOList;
    }

    @Override
    public void saveOrUpdateSpecGroup(SpecGroupDTO specGroupDTO) {
        this.saveOrUpdate(specGroupDTO.toEntity(SpecGroup.class));
    }
}
